<template>
  <div class="record-container">
    <el-card class="filter-card">
      <!-- 搜索筛选区域 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="载体" prop="zt">
          <el-select v-model="queryParams.zt" placeholder="请选择载体" clearable filterable style="width: 150px"
            :loading="dropdownLoading" @focus="handleSelectFocus('zt')">
            <el-option v-for="item in ztOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="房间号" prop="roomNumber">
          <el-input v-model="queryParams.roomNumber" placeholder="请输入房间号" clearable style="width: 150px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="房间状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择房间状态" clearable style="width: 150px">
            <el-option label="未出租" value="0" />
            <el-option label="占用中" value="1" />
            <el-option label="已出租" value="2" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="场地类型" prop="siteType">
          <el-select v-model="queryParams.siteType" placeholder="请选择场地类型" clearable style="width: 150px">
            <el-option label="办公场地" value="办公场地" />
            <el-option label="生产场地" value="生产场地" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="是否招商" prop="isAttractInvestment">
          <el-select v-model="queryParams.isAttractInvestment" placeholder="请选择是否招商" clearable style="width: 120px">
            <el-option label="招商中" :value="1" />
            <el-option label="不招商" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="资产类型" prop="assetType">
          <el-select v-model="queryParams.assetType" placeholder="请选择资产类型" clearable style="width: 150px">
            <el-option label="房间" :value="0" />
            <el-option label="工位" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮区域 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增房源</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="Edit" :disabled="single || !canEdit"
            @click="handleUpdate">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple || !canDelete"
            @click="handleDelete">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Collection" :disabled="mergeDisabled"
            @click="handleMergeClick">合并</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Scissor" :disabled="splitDisabled"
            @click="handleSplitClick">拆分</el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-card class="list-card" style="margin-top: 18px">
      <!-- 房源卡片列表 -->
      <div class="property-cards-container" v-loading="loading">
        <el-row :gutter="16">
          <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="3" v-for="property in propertyList" :key="property.id"
            class="property-card-col">
            <el-popover trigger="hover" placement="right" :show-after="150" :hide-after="100" width="320">
              <template #reference>
                <el-card class="property-card" :class="{ selected: selectedIds.includes(property.id) }"
                  @click="handleCardClick(property)">
                  <div class="property-image">
                    <img :src="property.image || roomImg" :alt="property.roomNumber" />
                    <div class="property-status" :class="'status-' + property.status">
                      {{ getStatusText(property.status) }}
                    </div>
                  </div>

                  <div class="property-info">
                    <div class="property-title">
                      <h3>{{ property.roomNumber }}</h3>
                    </div>

                    <div class="property-brief">
                      <span class="brief-item">{{ property.zt || "-" }}</span>
                      <span class="brief-dot">•</span>
                      <span class="brief-item">{{ (property.area || "-") + "㎡" }}</span>
                    </div>

                    <div class="property-actions">
                      <el-button type="success" size="small" @click.stop="handleEdit(property)"
                        :disabled="property.status !== 0">编辑</el-button>
                      <el-button type="danger" size="small" @click.stop="handleDelete(property)"
                        :disabled="property.status !== 0">删除</el-button>
                    </div>
                  </div>
                </el-card>
              </template>
              <div class="popover-details">
                <div class="popover-title">房间 {{ property.roomNumber }}</div>
                <div class="detail-item">
                  <span class="label">状态：</span><span class="value">{{ getStatusText(property.status) }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">载体：</span><span class="value">{{ property.zt || "-" }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">面积：</span><span class="value">{{ property.area || "-" }}㎡</span>
                </div>
                <div class="detail-item">
                  <span class="label">资产类型：</span><span class="value">{{ property.assetType === 0 ? "房间" :
                    (property.assetType === 1 ? "工位" : "-") }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">房源类型：</span><span class="value">{{ property.roomType || "-" }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">场地类型：</span><span class="value">{{ property.siteType || "-" }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">是否招商：</span><span class="value">{{
                    property.isAttractInvestment == 1
                    ? "招商中"
                    : property.isAttractInvestment == 0
                    ? "不招商"
                    : "未知"
                    }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">装修类型：</span><span class="value">{{ property.decorationType || "-" }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">功能分区：</span><span class="value">{{ property.functionalArea || "-" }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">区域：</span><span class="value">{{ property.region || "-" }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">企业ID：</span><span class="value">{{ property.companyId || "-" }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">合同编号：</span><span class="value">{{ property.contractNumber || "-" }}</span>
                </div>
                <!-- 备注 -->
                 <div class="detail-item">
                  <span class="label">备注：</span><span class="value">{{ property.remark || "-" }}</span>
                </div>
              </div>
            </el-popover>
          </el-col>
        </el-row>

        <!-- 空状态 -->
        <el-empty v-if="!loading && propertyList.length === 0" description="暂无房源数据" />
      </div>

      <!-- 分页组件 -->
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 房源详情对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form :model="form" :rules="rules" ref="propertyRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="房间号" prop="roomNumber">
              <el-input v-model="form.roomNumber" placeholder="请输入房间号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态">
                <el-option label="未出租" :value="0" />
                <el-option label="占用中" :value="1" />
                <el-option label="已出租" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="载体" prop="zt">
              <el-select v-model="form.zt" placeholder="请选择载体" clearable filterable :loading="dropdownLoading"
                @focus="handleSelectFocus('zt')">
                <el-option v-for="item in ztOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="面积(㎡)" prop="area">
              <el-input v-model="form.area" placeholder="请输入面积" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="资产类型" prop="assetType">
              <el-select v-model="form.assetType" placeholder="请选择资产类型">
                <el-option label="房间" :value="0" />
                <el-option label="工位" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房源类型" prop="roomType">
              <el-select v-model="form.roomType" placeholder="请选择房源类型" clearable>
                <el-option label="实体" value="实体" />
                <el-option label="虚拟" value="虚拟" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="场地类型" prop="siteType">
              <el-select v-model="form.siteType" placeholder="请选择场地类型">
                <el-option label="办公场地" value="办公场地" />
                <el-option label="生产场地" value="生产场地" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否招商" prop="isAttractInvestment">
              <el-select v-model="form.isAttractInvestment" placeholder="请选择是否招商">
                <el-option label="招商中" :value="1" />
                <el-option label="不招商" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="装修类型" prop="decorationType">
              <el-input v-model="form.decorationType" placeholder="请输入装修类型" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="功能分区" prop="functionalArea">
              <el-input v-model="form.functionalArea" placeholder="请输入功能分区" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="区域" prop="region">
              <el-input v-model="form.region" placeholder="请输入区域" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 拆分对话框 -->
    <el-dialog :title="splitTitle" v-model="splitOpen" width="900px" append-to-body>
      <div style="margin-bottom: 10px; color: #909399">
        原房间可拆分总面积：{{ splitMaxArea }}㎡；已分配：{{ splitTotalArea }}㎡；剩余：{{
        splitRemainingArea
        }}㎡
      </div>
      <div>
        <el-button type="primary" plain icon="Plus" @click="addSplitRow" :disabled="!canAddMore">新增拆分房源</el-button>
      </div>
      <div style="margin-top: 12px">
        <div v-for="(item, idx) in splitForms" :key="idx" class="split-form-block">
          <el-card shadow="never" style="margin-bottom: 12px">
            <template #header>
              <div style="display: flex; justify-content: space-between; align-items: center">
                <span>拆分房源 {{ idx + 1 }}</span>
                <el-button size="small" type="danger" plain icon="Delete" @click="removeSplitRow(idx)"
                  :disabled="splitForms.length === 1">移除</el-button>
              </div>
            </template>
            <el-form :model="item" :rules="splitItemRules" ref="splitItemRefs" label-width="120px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="房间号" prop="roomNumber" required>
                    <el-input v-model="item.roomNumber" placeholder="请输入房间号" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="状态" prop="status" required>
                    <el-select v-model="item.status" placeholder="请选择状态">
                      <el-option label="未出租" :value="0" />
                      <el-option label="占用中" :value="1" />
                      <el-option label="已出租" :value="2" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="载体" prop="zt" required>
                    <el-select v-model="item.zt" placeholder="请选择载体" clearable filterable :loading="dropdownLoading"
                      @focus="handleSelectFocus('zt')">
                      <el-option v-for="opt in ztOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="面积(㎡)" prop="area" required>
                    <el-input v-model="item.area" placeholder="请输入面积" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="资产类型" prop="assetType" required>
                    <el-select v-model="item.assetType" placeholder="请选择资产类型">
                      <el-option label="房间" :value="0" />
                      <el-option label="工位" :value="1" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="房源类型" prop="roomType">
                    <el-select v-model="item.roomType" placeholder="请选择房源类型" clearable>
                      <el-option label="实体" value="实体" />
                      <el-option label="虚拟" value="虚拟" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="场地类型" prop="siteType" required>
                    <el-select v-model="item.siteType" placeholder="请选择场地类型">
                      <el-option label="办公场地" value="办公场地" />
                      <el-option label="生产场地" value="生产场地" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="是否招商" prop="isAttractInvestment" required>
                    <el-select v-model="item.isAttractInvestment" placeholder="请选择是否招商">
                      <el-option label="招商中" :value="1" />
                      <el-option label="不招商" :value="0" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="装修类型">
                    <el-input v-model="item.decorationType" placeholder="请输入装修类型" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="功能分区">
                    <el-input v-model="item.functionalArea" placeholder="请输入功能分区" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="区域">
                    <el-input v-model="item.region" placeholder="请输入区域" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="备注">
                    <el-input v-model="item.remark" type="textarea" :rows="3" placeholder="请输入备注" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-card>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-tag v-if="splitForms.length < 2" type="warning" effect="plain" size="small" style="margin-right: 8px">
            ! 至少添加两个拆分房源
          </el-tag>
          <el-tag v-if="splitTotalArea > splitMaxArea" type="danger" effect="plain" size="small"
            style="margin-right: 2%">
            ! 拆分总面积已超出可用面积
          </el-tag>
          <el-button type="primary" :disabled="
              splitForms.length < 2 ||
              splitTotalArea <= 0 ||
              splitTotalArea > splitMaxArea
            " @click="submitSplit">确 定</el-button>
          <el-button @click="cancelSplit">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 合并对话框 -->
    <el-dialog :title="mergeTitle" v-model="mergeOpen" width="800px" append-to-body>
      <div style="margin-bottom: 10px; color: #909399">
        已选择房源数：{{ mergeSelectedRooms.length }} 个；合并后面积：{{
        mergeTotalArea
        }}㎡
      </div>
      <el-form :model="mergeForm" :rules="mergeRules" ref="mergeRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="房间号" prop="roomNumber">
              <el-input v-model="mergeForm.roomNumber" placeholder="请输入房间号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="mergeForm.status" placeholder="请选择状态">
                <el-option label="未出租" :value="0" />
                <el-option label="占用中" :value="1" />
                <el-option label="已出租" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="载体" prop="zt" required>
              <el-select v-model="mergeForm.zt" placeholder="请选择载体" clearable filterable :loading="dropdownLoading"
                @focus="handleSelectFocus('zt')">
                <el-option v-for="item in ztOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="面积(㎡)" prop="area" required>
              <el-input :model-value="mergeTotalArea" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="资产类型" prop="assetType" required>
              <el-select v-model="mergeForm.assetType" placeholder="请选择资产类型">
                <el-option label="房间" :value="0" />
                <el-option label="工位" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房源类型" prop="roomType">
              <el-select v-model="mergeForm.roomType" placeholder="请选择房源类型" clearable>
                <el-option label="实体" value="实体" />
                <el-option label="虚拟" value="虚拟" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="场地类型" prop="siteType" required>
              <el-select v-model="mergeForm.siteType" placeholder="请选择场地类型">
                <el-option label="办公场地" value="办公场地" />
                <el-option label="生产场地" value="生产场地" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否招商" prop="isAttractInvestment" required>
              <el-select v-model="mergeForm.isAttractInvestment" placeholder="请选择是否招商">
                <el-option label="招商中" :value="1" />
                <el-option label="不招商" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="装修类型" prop="decorationType">
              <el-input v-model="mergeForm.decorationType" placeholder="请输入装修类型" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="功能分区" prop="functionalArea">
              <el-input v-model="mergeForm.functionalArea" placeholder="请输入功能分区" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="区域" prop="region">
              <el-input v-model="mergeForm.region" placeholder="请输入区域" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="mergeForm.remark" type="textarea" :rows="3" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 新增被合并房源明细只读卡片 -->
      <div v-if="mergeSelectedRooms.length" style="margin: 18px 0 0 0">
        <div style="
            font-size: 13px;
            color: #666;
            margin-bottom: 6px;
            letter-spacing: 1px;
            font-weight: bold;
          ">
          合并房源明细
        </div>
        <el-row :gutter="8">
          <el-col :xs="24" :sm="12" :md="8" v-for="room in mergeSelectedRooms" :key="room.id">
            <el-card shadow="never" style="
                background: #f5f7fa;
                color: #999;
                margin-bottom: 8px;
                border: 1px dashed #bbb;
              ">
              <div style="display: flex; align-items: center; justify-content: space-between">
                <span style="font-size: 15px; font-weight: bold; color: #888">
                  房间号：{{ room.roomNumber }}
                </span>
                <span style="font-size: 13px; color: #bbb">状态：{{ getStatusText(room.status) }}</span>
              </div>
              <div style="margin-top: 4px; font-size: 13px; color: #777">
                面积：{{ room.area || "-" }} ㎡ ｜ 分区：{{
                room.functionalArea || "-"
                }}
                ｜ 载体：{{ room.zt || "-" }} ｜ 是否招商：{{
                getIsAttractInvestmentText(room.isAttractInvestment)
                }}
                ｜ 场地类型：{{ room.siteType || "-" }}
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-tag v-if="mergeSelectedRooms.some((r) => Number(r.status) !== 0)" type="danger" effect="plain"
            size="small" style="margin-right: 2%">
            ! 仅"未出租"的房源可合并
          </el-tag>
          <el-tag v-if="mergeZtInconsistent" type="danger" effect="plain" size="small" style="margin-right: 2%">
            ! 只能合并相同载体的房源
          </el-tag>
          <el-button type="primary" :disabled="mergeSubmitDisabled" @click="submitMerge">确 定</el-button>
          <el-button @click="cancelMerge">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PropertyList">
import { ref, reactive, onMounted, getCurrentInstance, nextTick, computed } from "vue";
import {
  getPropertyList,
  addProperty,
  updateProperty,
  deleteProperty,
  splitRooms,
  mergeRooms,
} from "@/api/property";
import roomImg from "@/assets/roomImg.png";
import { getBaseCodeInfoList } from "@/api/AttractInvestment/baseCode/index.js";

const { proxy } = getCurrentInstance();

// 响应式数据
const propertyList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const selectedIds = ref([]);
const single = ref(true);
const multiple = ref(true);
const canEdit = ref(true); // 是否可以编辑（只有未出租状态才可以）
const canDelete = ref(true); // 是否可以删除（只有未出租状态才可以）
const total = ref(0);
const open = ref(false);
const title = ref("");
// 合并/拆分控制
const splitOpen = ref(false);
const splitTitle = ref("拆分房源");
const splitForms = ref([
  {
    roomNumber: "",
    decorationType: "",
    functionalArea: "",
    zt: "",
    contractNumber: "",
    region: "",
    area: "",
    status: undefined,
    assetType: undefined,
    roomType: "",
    remark: "",
  },
]);
const splitSourceProperty = ref(null);
const splitMaxArea = computed(() => Number(splitSourceProperty.value?.area || 0));
const splitTotalArea = computed(() => {
  return splitForms.value.reduce((sum, cur) => {
    const n = Number(cur.area);
    return sum + (isNaN(n) ? 0 : n);
  }, 0);
});
const splitRemainingArea = computed(() => {
  const remain = splitMaxArea.value - splitTotalArea.value;
  return remain < 0 ? 0 : remain;
});
const canAddMore = computed(() => splitRemainingArea.value > 0);
const splitDisabled = computed(() => {
  if (selectedIds.value.length !== 1) return true;
  const p = propertyList.value.find((x) => x.id === selectedIds.value[0]);
  return !p || Number(p.status) !== 0;
});
const mergeDisabled = computed(() => {
  if (selectedIds.value.length < 2) return true;
  const rooms = propertyList.value.filter((x) => selectedIds.value.includes(x.id));
  // 检查是否有非未出租状态的房间
  if (rooms.some((r) => Number(r.status) !== 0)) return true;
  // 检查载体是否一致
  const ztSet = new Set(rooms.map((r) => r.zt).filter(Boolean));
  if (ztSet.size > 1) return true; // 载体不一致
  return false;
});
// 合并控制
const mergeOpen = ref(false);
const mergeTitle = ref("合并房源");
const mergeForm = reactive({
  roomNumber: "",
  decorationType: "",
  functionalArea: "",
  zt: "",
  contractNumber: "",
  region: "",
  area: "",
  status: undefined,
  assetType: undefined,
  roomType: "",
  remark: "",
});
const mergeSelectedRooms = computed(() =>
  propertyList.value.filter((p) => selectedIds.value.includes(p.id))
);
const mergeTotalArea = computed(() =>
  mergeSelectedRooms.value.reduce((sum, r) => sum + (Number(r.area) || 0), 0)
);
const mergeZtInconsistent = computed(() => {
  const ztSet = new Set(mergeSelectedRooms.value.map((r) => r.zt).filter(Boolean));
  return ztSet.size > 1;
});
const mergeSubmitDisabled = computed(() => {
  if (mergeSelectedRooms.value.length < 2) return true;
  if (mergeSelectedRooms.value.some((r) => Number(r.status) !== 0)) return true;
  // 检查载体是否一致
  const ztSet = new Set(mergeSelectedRooms.value.map((r) => r.zt).filter(Boolean));
  if (ztSet.size > 1) return true;
  if (!mergeForm.roomNumber) return true;
  if (mergeForm.status === undefined || mergeForm.status === null) return true;
  if (mergeForm.assetType === undefined || mergeForm.assetType === null) return true;
  return false;
});
const mergeRules = reactive({
  roomNumber: [{ required: true, message: "房间号不能为空", trigger: "blur" }],
  status: [{ required: true, message: "状态不能为空", trigger: "change" }],
  assetType: [{ required: true, message: "资产类型不能为空", trigger: "change" }],
});

// 载体下拉
const dropdownLoading = ref(false);
const ztOptions = ref([]);
const handleSelectFocus = async (key) => {
  if (key !== "zt") return;
  if (ztOptions.value && ztOptions.value.length > 0) return; // 已加载过
  dropdownLoading.value = true;
  try {
    // 与 customerList.vue 一致：bigCategory=35 → projectList（载体/项目）
    const res = await getBaseCodeInfoList({ bigCategory: 35 });
    if (res && res.code === 200 && Array.isArray(res.rows)) {
      ztOptions.value = res.rows.map((item) => ({
        label: item.content,
        value: item.content,
      }));
    } else {
      ztOptions.value = [];
    }
  } catch (e) {
    console.error("获取载体下拉失败:", e);
    ztOptions.value = [];
  } finally {
    dropdownLoading.value = false;
  }
};
// 多表单校验规则与引用
const splitItemRules = reactive({
  roomNumber: [{ required: true, message: "房间号不能为空", trigger: "blur" }],
  status: [{ required: true, message: "状态不能为空", trigger: "change" }],
  area: [
    { required: true, message: "面积不能为空", trigger: "blur" },
    {
      validator: (_rule, value, callback) => {
        const num = Number(value);
        if (!value || isNaN(num) || num <= 0) {
          callback(new Error("请输入有效的面积"));
          return;
        }
        callback();
      },
      trigger: "blur",
    },
  ],
  zt: [{ required: true, message: "载体不能为空", trigger: "change" }],
  assetType: [{ required: true, message: "资产类型不能为空", trigger: "change" }],
});
const splitItemRefs = ref([]);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 24,
  roomNumber: undefined,
  roomType: undefined,
  status: undefined,
  region: undefined,
  minArea: undefined,
  maxArea: undefined,
  siteType: undefined,
  isAttractInvestment: undefined,
  assetType: undefined,
});

// 表单数据（与卡片详情字段对齐）
const form = reactive({
  id: undefined,
  roomNumber: "",
  decorationType: "",
  functionalArea: "",
  companyId: "",
  zt: "",
  contractNumber: "",
  region: "",
  area: "",
  status: undefined,
  isAttractInvestment: undefined, // 0-不招商，1-招商中
  siteType: undefined, // 办公场地/生产场地
  assetType: undefined, // 0-房间，1-工位
  roomType: "", // 房源类型：实体、虚拟
  remark: "",
});

// 表单验证规则
const rules = reactive({
  roomNumber: [{ required: true, message: "房间号不能为空", trigger: "blur" }],
  status: [{ required: true, message: "状态不能为空", trigger: "change" }],
  area: [{ required: true, message: "面积不能为空", trigger: "blur" }],
  zt: [{ required: true, message: "载体不能为空", trigger: "change" }],
  isAttractInvestment: [{ required: true, message: "请选择是否招商", trigger: "change" }],
  siteType: [{ required: true, message: "请选择场地类型", trigger: "change" }],
  assetType: [{ required: true, message: "资产类型不能为空", trigger: "change" }],
});

// 获取房源列表
const getList = () => {
  loading.value = true;
  getPropertyList(queryParams)
    .then((response) => {
      if (response.code === 200) {
        const rows = Array.isArray(response.rows) ? response.rows : [];
        propertyList.value = rows.map(mapRoomRow);
        console.log("房源列表数据:", propertyList.value);
        total.value = response.total || 0;
      } else {
        proxy.$modal.msgError(response.msg || "获取房源列表失败");
        propertyList.value = [];
        total.value = 0;
      }
    })
    .catch((error) => {
      console.error("获取房源列表失败:", error);
    })
    .finally(() => {
      setTimeout(() => {
        loading.value = false;
      }, 300);
    });
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = { 0: "未出租", 1: "占用中", 2: "已出租" };
  return statusMap[status] || status;
};

const getIsAttractInvestmentText = (isAttractInvestment) => {
  const isAttractInvestmentMap = { 0: "租用", 1: "自用", 2: "借用" };
  return isAttractInvestmentMap[isAttractInvestment] || isAttractInvestment;
};

// 渲染数据
const mapRoomRow = (row) => {
  return {
    id: row.id,
    roomNumber: row.roomNumber,
    decorationType: row.decorationType,
    functionalArea: row.functionalArea,
    zt: row.zt,
    contractNumber: row.contractNumber,
    region: row.region,
    area: row.area,
    status: row.status,
    createTime: row.createTime,
    updateTime: row.updateTime,
    isAttractInvestment: row.isAttractInvestment,
    siteType: row.siteType,
    assetType: row.assetType,
    roomType: row.roomType,
    remark: row.remark,
  };
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  proxy.resetForm("queryRef");
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 24,
    roomNumber: undefined,
    roomType: undefined,
    status: undefined,
    region: undefined,
    minArea: undefined,
    maxArea: undefined,
    siteType: undefined,
    isAttractInvestment: undefined,
    assetType: undefined,
  });
  getList();
};

// 卡片点击事件
const handleCardClick = (property) => {
  const index = selectedIds.value.indexOf(property.id);
  if (index > -1) {
    selectedIds.value.splice(index, 1);
  } else {
    selectedIds.value.push(property.id);
  }
  updateSelectionState();
};

// 更新选择状态
const updateSelectionState = () => {
  single.value = selectedIds.value.length !== 1;
  multiple.value = !selectedIds.value.length;

  // 检查选中的房间是否都是未出租状态（status === 0）
  const selectedProperties = propertyList.value.filter((item) =>
    selectedIds.value.includes(item.id)
  );

  // 编辑：只有选中一个且状态为未出租时才可以
  if (selectedIds.value.length === 1) {
    canEdit.value = selectedProperties[0]?.status === 0;
  } else {
    canEdit.value = false;
  }

  // 删除：所有选中的房间都必须是未出租状态
  if (selectedIds.value.length > 0) {
    canDelete.value = selectedProperties.every((item) => item.status === 0);
  } else {
    canDelete.value = false;
  }
};

// 查看详情
const handleView = (property) => {
  proxy.$modal.msgInfo(`查看房源 ${property.roomNumber} 的详情`);
};

// 编辑房源
const handleEdit = (property) => {
  // 检查房间状态
  if (property.status !== 0) {
    proxy.$modal.msgWarning("只有未出租状态的房间才可以编辑");
    return;
  }
  console.log("编辑房源:", property);
  Object.assign(form, {
    id: property.id,
    roomNumber: property.roomNumber || "",
    decorationType: property.decorationType || "",
    functionalArea: property.functionalArea || "",
    companyId: property.companyId || "",
    zt: property.zt || "",
    contractNumber: property.contractNumber || "",
    region: property.region || "",
    area: property.area || "",
    status: property.status ?? 0,
    isAttractInvestment: property.isAttractInvestment !== undefined && property.isAttractInvestment !== null ? property.isAttractInvestment : 1,
    siteType: property.siteType || "办公场地",
    assetType: property.assetType,
    roomType: property.roomType || "",
    remark: property.remark || "",
  });
  open.value = true;
  title.value = "修改房源";
};

// 修改按钮操作
const handleUpdate = () => {
  if (selectedIds.value.length !== 1) {
    proxy.$modal.msgWarning("请选择一个房源进行修改");
    return;
  }
  const property = propertyList.value.find((item) => item.id === selectedIds.value[0]);
  if (property) {
    handleEdit(property);
  }
};

// 新增房源
const handleAdd = () => {
  // 先重置模型数据
  reset();
  // 打开对话框后再重置表单校验与控件值，确保 $refs 存在
  open.value = true;
  title.value = "新增房源";
  nextTick(() => {
    proxy.resetForm("propertyRef");
  });
};

// 点击拆分
const handleSplitClick = () => {
  if (splitDisabled.value) return;
  const source = propertyList.value.find((x) => x.id === selectedIds.value[0]);
  splitSourceProperty.value = source || null;
  splitForms.value = [
    {
      roomNumber: "",
      decorationType: source?.decorationType || "",
      functionalArea: source?.functionalArea || "",
      zt: source?.zt || "",
      contractNumber: "",
      region: source?.region || "",
      area: "",
      status: undefined,
      assetType: source?.assetType,
      roomType: source?.roomType || "",
      remark: "",
    },
  ];
  splitOpen.value = true;
};

// 提交拆分
const submitSplit = () => {
  // 触发表单校验以显示错误
  const refsAny = proxy.$refs && proxy.$refs.splitItemRefs;
  const formRefs = Array.isArray(refsAny) ? refsAny : refsAny ? [refsAny] : [];
  const validateAll = formRefs.map(
    (f) =>
      new Promise((resolve) => {
        if (!f || !f.validate) return resolve(false);
        f.validate((valid) => resolve(valid));
      })
  );
  Promise.all(validateAll).then((vals) => {
    if (vals.length && vals.some((v) => v === false)) return;
    // 基础校验
    if (!splitForms.value.length) {
      proxy.$modal.msgWarning("请至少添加一个拆分房源");
      return;
    }
    if (splitForms.value.length < 2) {
      proxy.$modal.msgWarning("请至少拆分为两个房源");
      return;
    }
    if (!splitSourceProperty.value || !splitSourceProperty.value.id) {
      proxy.$modal.msgWarning("未识别到原房源，无法提交拆分");
      return;
    }
    // 字段与面积校验
    for (let i = 0; i < splitForms.value.length; i++) {
      const item = splitForms.value[i];
      if (!item.roomNumber) {
        proxy.$modal.msgWarning(`第${i + 1}个房源房间号不能为空`);
        return;
      }
      const areaNum = Number(item.area);
      if (!item.area || isNaN(areaNum) || areaNum <= 0) {
        proxy.$modal.msgWarning(`第${i + 1}个房源面积需为正数`);
        return;
      }
    }
    if (splitTotalArea.value > splitMaxArea.value) {
      proxy.$modal.msgWarning("拆分总面积不能超过原房间面积");
      return;
    }
    // 一次性提交拆分：传递原房间ID与新房源数组
    const payload = {
      id: splitSourceProperty.value.id,
      roomArray: splitForms.value.map((f) => ({
        roomNumber: f.roomNumber,
        decorationType: f.decorationType,
        functionalArea: f.functionalArea,
        zt: f.zt,
        contractNumber: f.contractNumber,
        region: f.region,
        area: f.area,
        status: f.status,
        assetType: f.assetType,
        roomType: f.roomType,
        remark: f.remark,
      })),
    };
    splitRooms(payload)
      .then((res) => {
        if (res && res.code === 200) {
          proxy.$modal.msgSuccess("拆分成功");
          splitOpen.value = false;
          getList();
        } else {
          proxy.$modal.msgError((res && res.msg) || "拆分失败");
        }
      })
      .catch((e) => {
        console.error("拆分失败:", e);
      });
  });
};

const cancelSplit = () => {
  splitOpen.value = false;
};

// 合并流程
const handleMergeClick = () => {
  if (mergeDisabled.value) return;
  const first = propertyList.value.find((x) => x.id === selectedIds.value[0]);
  Object.assign(mergeForm, {
    roomNumber: "",
    decorationType: first?.decorationType || "",
    functionalArea: first?.functionalArea || "",
    zt: first?.zt || "",
    contractNumber: "",
    region: first?.region || "",
    area: mergeTotalArea.value,
    status: undefined,
    assetType: first?.assetType,
    roomType: first?.roomType || "",
    remark: "",
  });
  mergeOpen.value = true;
  nextTick(() => proxy.resetForm && proxy.resetForm("mergeRef"));
};

// 提交合并前验证表单
const submitMerge = () => {
  // 表单规则校验
  const mergeRef = proxy.$refs && proxy.$refs.mergeRef;
  if (mergeRef && mergeRef.validate) {
    mergeRef.validate((valid) => {
      if (!valid) return;
      doSubmitMerge();
    });
  } else {
    doSubmitMerge();
  }
};

// 合并提交
const doSubmitMerge = () => {
  // 检查载体是否一致
  if (mergeZtInconsistent.value) {
    proxy.$modal.msgWarning("只能合并相同载体的房源");
    return;
  }

  const payload = {
    ...mergeForm,
    area: mergeTotalArea.value,
    roomIds: selectedIds.value.map((x) => String(x)),
  };
  mergeRooms(payload)
    .then((response) => {
      if (response.code === 200) {
        proxy.$modal.msgSuccess("合并成功");
        mergeOpen.value = false;
        mergeDisabled.value = false;
        selectedIds.value = [];
        getList();
      } else {
        proxy.$modal.msgError(response.msg || "合并失败");
      }
    })
    .catch((e) => {
      console.error("合并失败:", e);
    });
};

const cancelMerge = () => {
  mergeOpen.value = false;
};

// 多表单操作
const addSplitRow = () => {
  if (!canAddMore.value) return;
  splitForms.value.push({
    roomNumber: "",
    decorationType: splitSourceProperty.value?.decorationType || "",
    functionalArea: splitSourceProperty.value?.functionalArea || "",
    zt: splitSourceProperty.value?.zt || "",
    contractNumber: "",
    region: splitSourceProperty.value?.region || "",
    area: "",
    status: undefined,
    assetType: splitSourceProperty.value?.assetType,
    roomType: splitSourceProperty.value?.roomType || "",
    remark: "",
  });
};

const removeSplitRow = (idx) => {
  if (splitForms.value.length === 1) return;
  splitForms.value.splice(idx, 1);
};

// 删除房源
const handleDelete = (property) => {
  const ids = property?.id ? [property.id] : selectedIds.value;

  // 检查要删除的房间状态
  const propertiesToDelete = property?.id
    ? [property]
    : propertyList.value.filter((item) => ids.includes(item.id));

  const hasRentedProperty = propertiesToDelete.some((item) => item.status !== 0);
  if (hasRentedProperty) {
    proxy.$modal.msgWarning("只有未出租状态的房间才可以删除");
    return;
  }

  proxy.$modal
    .confirm(`是否确认删除选中的${ids.length}个房源？`)
    .then(() => {
      deleteProperty(ids.join(","))
        .then((response) => {
          if (response.code === 200) {
            proxy.$modal.msgSuccess("删除成功");
            getList();
            selectedIds.value = [];
            updateSelectionState();
          } else {
            proxy.$modal.msgError(response.msg || "删除失败");
          }
        })
        .catch((error) => {
          console.error("删除房源失败:", error);
        });
    })
    .catch(() => {});
};

// 重置表单
const reset = () => {
  Object.assign(form, {
    id: undefined,
    roomNumber: "",
    decorationType: "",
    functionalArea: "",
    companyId: "",
    zt: "",
    contractNumber: "",
    region: "",
    area: "",
    status: undefined,
    isAttractInvestment: undefined,
    siteType: undefined,
    assetType: undefined,
    roomType: "",
    remark: "",
  });
  proxy.resetForm("propertyRef");
};

// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
};

// 提交表单
const submitForm = () => {
  proxy.$refs["propertyRef"].validate((valid) => {
    if (valid) {
      if (form.id) {
        // 修改房源
        updateProperty(form)
          .then((response) => {
            if (response.code === 200) {
              proxy.$modal.msgSuccess("修改成功");
              open.value = false;
              getList();
            } else {
              proxy.$modal.msgError(response.msg || "修改失败");
            }
          })
          .catch((error) => {
            console.error("修改房源失败:", error);
          });
      } else {
        // 新增房源
        addProperty(form)
          .then((response) => {
            if (response.code === 200) {
              proxy.$modal.msgSuccess("新增成功");
              open.value = false;
              getList();
            } else {
              proxy.$modal.msgError(response.msg || "新增失败");
            }
          })
          .catch((error) => {
            console.error("新增房源失败:", error);
          });
      }
    }
  });
};

// 组件挂载时获取数据
onMounted(() => {
  getList();
});
</script>

<style scoped>
.property-page {
  display: flex;
  flex-direction: column;
  min-height: 90vh;
}

.property-cards-container {
  margin-bottom: 20px;
  /* 占据剩余空间，确保分页组件贴底 */
  flex: 1;
}

.property-card-col {
  margin-bottom: 14px;
}

.property-card {
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.property-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.property-card.selected {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.property-image {
  position: relative;
  height: 120px;
  overflow: hidden;
  border-radius: 4px;
  margin-bottom: 10px;
}

.property-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
}

.property-status {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
  color: white;
}

.property-status.status-0 {
  /* 未出租 */
  background-color: #67c23a;
}

.property-status.status-1 {
  /* 占用中 */
  background-color: #e6a23c;
}

.property-status.status-2 {
  /* 已出租 */
  background-color: #f56c6c;
}

.property-info {
  padding: 0 2px 8px;
}

.property-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
}

.property-title h3 {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.property-brief {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #606266;
  margin-bottom: 10px;
}

.property-brief .brief-dot {
  color: #c0c4cc;
}

.property-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 15px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #606266;
}

.detail-item .label {
  color: #909399;
  display: inline-block;
  width: 72px;
  text-align: right;
}

.detail-item .value {
  color: #303133;
}

.property-description {
  margin-bottom: 15px;
}

.property-description p {
  margin: 0;
  font-size: 13px;
  color: #909399;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.property-actions {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.property-actions .el-button {
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .property-actions {
    flex-direction: column;
  }

  .property-actions .el-button {
    margin-bottom: 5px;
  }
}

/* 空状态样式 */
.el-empty {
  margin: 50px 0;
}

/* Popover detail styles */
.popover-details {
  font-size: 13px;
  line-height: 1.5;
}

.popover-details .popover-title {
  font-weight: 600;
  margin-bottom: 8px;
  color: #303133;
}
</style>
